// $Id: RunBatch.cs 68 2008-05-09 16:11:33Z nvivo $

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DBLGen.UI;

namespace DBLGen.GUI.Forms
{
    public partial class RunBatch : Form
    {
        private Table[] _targetTables;
        PluginInfo _currentPlugin;
        PluginSettingsEditor _editor;

        public RunBatch(Table[] targetTables)
        {
            if (targetTables == null)
                throw new ArgumentNullException("targetTables");

            _targetTables = targetTables;

            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void RunBatch_Load(object sender, EventArgs e)
        {
            lbPlugins.DataSource = new BindingSource(Plugin.GetBatchPlugins(), null);
            lbTargetTables.DataSource = new BindingSource(_targetTables, null);

            for (int i = _targetTables.Length - 1; i >= 0; i--)
                lbTargetTables.SetSelected(i, true);
        }

        private void lbPlugins_SelectedIndexChanged(object sender, EventArgs e)
        {
            _currentPlugin = lbPlugins.SelectedItem as PluginInfo;

            if (_currentPlugin != null)
            {
                panelSettings.Controls.Clear();
                _editor = _currentPlugin.CreateEditor();

                if (_editor != null)
                    panelSettings.Controls.Add(_editor);

                PluginSettings settings = _currentPlugin.CreateSettings();
                _editor.LoadSettings(settings);
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (_currentPlugin != null)
            {
                BatchPlugin bp = (BatchPlugin) _currentPlugin.CreatePlugin();
                bp.Settings = _editor.SaveSettings();

                Table[] targets = GetSelectedTables();

                foreach (Table t in targets)
                    bp.Process(t);

                MessageBox.Show("Done!");
                Close();
            }
        }

        private Table[] GetSelectedTables()
        {
            List<Table> selectedTables = new List<Table>();

            foreach (int i in lbTargetTables.SelectedIndices)
                selectedTables.Add((Table) lbTargetTables.Items[i]);

            return selectedTables.ToArray();
        }
    }
}
